
class PaymentsController < ApplicationController
  before_action :require_logined

  def generate_pay
    order = Order.find_by_order_no(params[:order_no])
    @payment = Payment.create_or_update_payment!(current_user, order, get_pay_type)
    PaymentService.do_pay(@payment)
  end

  def get_charge
    payment = Payment.find(params[:id])
    @charge = payment.generate_pay
    render json: @charge
  end

  def callback
    @flag = false
    out_trade_no = params[:out_trade_no]
    payment = Payment.where("payment_no = ? or repay_no = ?", out_trade_no, out_trade_no).first
    raise ActiveRecord::RecordNotFound if payment.nil?

    @order = payment.order
    raise ActiveRecord::RecordNotFound if @order.user_id != current_user.id
    if is_successful?
      @flag = true
      do_success(@order)
    else
      do_fail(@order)
    end
  end

  private

  def is_successful?
    (params[:is_success] == "T" && params[:trade_status] == "TRADE_SUCCESS") || params[:result] == 'success'
  end

  def get_pay_type
    mobile? ? Payment::PayType::ALIPAY_WAP : Payment::PayType::ALIPAY_PC_DIRECT
  end

  def charge_callback order
    if is_successful?
      do_success(order)
    else
      do_fail(order)
    end
  end

  def do_success order
    if order.normal?
      PaymentService.normal_pay_callback(order)
    else
      PaymentService.chuang_pay_callback(order)
    end
  end

  def do_fail order
  end


end
